﻿using System;
using Nelibur.ObjectMapper.Core.Extensions;

namespace Nelibur.ObjectMapper.Mappers.Classes
{
    internal abstract class ClassMapper<TSource, TTarget> : MapperOf<TSource, TTarget>
    {
        protected virtual TTarget CreateTargetInstance()
        {
            throw new NotImplementedException();
        }

        protected abstract TTarget MapClass(TSource source, TTarget target);

        protected override TTarget MapCore(TSource source, TTarget target)
        {
            if(target.IsNull())
            {
                target = CreateTargetInstance();
            }
            TTarget result = MapClass(source, target);
            return result;
        }

        protected virtual TTarget MapClassObjects(TSource source, TTarget target)
        {
            return target;
        }

        public override void MapObjects(object source, object target)
        {
            try
            {
                this.MapClassObjects((TSource)source, (TTarget)target);
            }
            catch(Exception ex)
            {
                var str = $"{typeof(TSource).FullName} --> {typeof(TTarget).FullName} 的引用类型成员转换失败";
                //var data = Newtonsoft.Json.JsonConvert.SerializeObject(source);
                //str = $"{str},SOURCE:{data}";
                throw new Exception(str, ex);
            }
        }
    }
}
